﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data;
using RedemptoristRetreatCenter.DatabaseUtility;

namespace RedemptoristRetreatCenter
{
    public partial class ViewRetreats : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable retreatTable = new DataTable();
            DataRow tableRow = null;

            retreatTable.Columns.Add(new DataColumn("Title", typeof(string)));
            retreatTable.Columns.Add(new DataColumn("Description", typeof(string)));
            retreatTable.Columns.Add(new DataColumn("Duration", typeof(float)));

            RetreatUtility retreatUtility = new RetreatUtility();
            List<RetreatInfo> retreatInfoList = retreatUtility.getAllRetreats();

            foreach (RetreatInfo retreatInfo in retreatInfoList)
            {
                tableRow = retreatTable.NewRow();
                tableRow["Title"] = retreatInfo.title;
                tableRow["Description"] = retreatInfo.description;
                tableRow["Duration"] = retreatInfo.duration;

                retreatTable.Rows.Add(tableRow);
                // this will be used on edit page so schedule can be prepopulated
                string rowIndexScheduleIdXref = String.Format("rowIndexScheduleIdXref_{0}", retreatTable.Rows.Count);
                Session[rowIndexScheduleIdXref] = retreatInfo.retreatId;
            }

            ViewState["CurrentTable"] = retreatTable;

            GridView1.DataSource = retreatTable;
            GridView1.DataBind();

            showAddRetreatButton();

        }

        private void showAddRetreatButton()
        {
            if (Session["isAdmin"] != null && (bool)Session["isAdmin"] == true)
            {
                addRetreat.Visible = true;
            }
        }

        protected void addRetreat_Click(object sender, EventArgs e)
        {
            Response.Redirect("AddRetreat.aspx");            
        }

        private void redirectPage()
        {
            // get schedule id from session varibles saved in load complete
            int xrefId;

            if (GridView1.SelectedIndex < 0)
            {   // selected index < 0 when clicking select/edit on 1st row
                xrefId = 1;
            }
            else
            {
                xrefId = GridView1.SelectedIndex + 1;
            }
            string sessionVariable = String.Format("rowIndexScheduleIdXref_{0}", xrefId);
            Response.Redirect("~/EditRetreat.aspx?ID=" + Session[sessionVariable].ToString());

        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            redirectPage();
        }
    }
}